<template>
  <div>
    <el-card>
      <el-button type="primary" icon="Plus" @click="addTrademark"
        >添加品牌</el-button
      >
      <el-table border stripe style="margin: 10px 0" :data="trademarkList">
        <el-table-column
          label="序号"
          align="center"
          width="180px"
          type="index"
        ></el-table-column>
        <el-table-column
          label="品牌名称"
          align="center"
          prop="tmName"
        ></el-table-column>
        <el-table-column label="品牌logo" align="center">
          <template #="{ row }">
            <img
              :src="
                row.logoUrl.slice(0, 7) === 'http://'
                  ? row.logoUrl
                  : 'http://' + row.logoUrl
              "
              style="width: 120px; height: 120px"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <!--@vue-ignore-->
          <template #="{ row }">
            <el-button
              icon="Edit"
              type="success"
              @click="updateTrademark(row)"
            ></el-button>
            <el-button icon="Delete" type="danger"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @current-change="changePage"
        @size-change="sizeChange"
        :pager-count="9"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[3, 4, 5, 6]"
        layout="prev, pager,next, jumper,->,total, sizes"
        :total="total"
      />
    </el-card>
    <el-dialog
      v-model="dialogFormVisible"
      :title="isUpdate ? '修改品牌' : '添加品牌'"
    >
      <el-form style="width: 80%" :model="trademarkData" :rules="rules" ref="formRef">
        <el-form-item label="品牌管理" lable-width="100px" prop="tmName">
          <el-input
            placeholder="请输入品牌名称"
            v-model="trademarkData.tmName"
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌logo" lable-width="100px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkData.logoUrl !== ''"
              :src="trademarkData.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="confirm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import {
  reqAddOrUpdateTrademark,
  reqHasTrademark,
} from "../api/product/trademark";
import type { TradeMark, TradeMarkData } from "../api/product/trademark/type";
import { ElMessage, type UploadProps } from "element-plus";
const currentPage = ref<number>(1);
const pageSize = ref<number>(5);
const total = ref<number>(0);
const isUpdate = ref<boolean>(false);
const trademarkList = ref<TradeMark[]>([]);
const formRef = ref()
const dialogFormVisible = ref<boolean>(false);
const trademarkData = reactive<TradeMark>({
  tmName: "",
  logoUrl: "",
});
onMounted(() => {
  getHasTrademark();
});
const updateTrademark = (row: any) => {
  formRef.value?.clearValidate('tmName')
  formRef.value?.clearValidate('logoUrl')
  isUpdate.value = true;
  dialogFormVisible.value = true;
  trademarkData.id = row.id
  trademarkData.tmName = row.tmName;
  trademarkData.logoUrl =
    row.logoUrl.slice(0, 7) === "http://"
      ? row.logoUrl
      : "http://" + row.logoUrl;
};
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  _uploadFile
) => {
  trademarkData.logoUrl = response.data;
  //图片上传成功清除校验
  formRef.value.clearValidate('logoUrl')
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  console.log("raw", rawFile);
  if (
    rawFile.type === "image/png" ||
    rawFile.type === "image/jpeg" ||
    rawFile.type === "image/gif"
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true;
    } else {
      ElMessage({
        type: "error",
        message: "文件大小不能超过4M",
      });
      return false;
    }
  } else {
    ElMessage({
      type: "error",
      message: "文件类型应为图片",
    });
    return false;
  }
};
const getHasTrademark = async (pager = 1) => {
    currentPage.value = pager
    const res: TradeMarkData = await reqHasTrademark(
      currentPage.value,
      pageSize.value
    );
    total.value = res.data.total;
    trademarkList.value = res.data.records;
};
const addTrademark = () => {
  isUpdate.value = false;
  trademarkData.tmName = "";
  trademarkData.logoUrl = "";
  dialogFormVisible.value = true;
  formRef.value?.clearValidate('tmName')
  formRef.value?.clearValidate('logoUrl')
};
const changePage = () => {
  getHasTrademark(currentPage.value);
};
const sizeChange = () => {
  currentPage.value = 1;
  getHasTrademark();
};
const cancel = () => {
  dialogFormVisible.value = false;
};
const confirm = async () => {
  //对表单的全部内容进行校验(接收回调函数或返回Promise对象)
  //等待Promise通过才能发请求
  await formRef.value.validate()
  const res = await reqAddOrUpdateTrademark(trademarkData);
  if (res.code === 200) {
    ElMessage({
      type: "success",
      message: trademarkData.id?"修改成功":"添加成功",
    });
    getHasTrademark(trademarkData.id?currentPage.value:1);
  } else {
    ElMessage({
      type: "error",
      message: trademarkData.id?"修改失败":"添加失败",
    });
  }
  dialogFormVisible.value = false;
  console.log(res);
};
const validatorTmName = (_rule:any,value:any,callBack:any) => {
  if(value.trim().length >= 1){
    callBack()
  }else{
    callBack(new Error('品牌名称长度不能小于1'))
  }
}
//自定义校验规则
const validatorLogoUrl = (_rule:any,value:any,callBack:any) => {
  if(value){
    callBack()
  }else{
    callBack(new Error('logo图片不能为空'))
  }
}
const rules = {
  tmName:[
    {
      required:true,trigger:'blur',validator:validatorTmName
    }
  ],
  logoUrl:[
    {
      required:true,trigger:'blur',validatorLogoUrl
    }
  ]
}
</script>
<style scoped lang="scss">
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  border: 1px dashed #8c939d;
}
</style>
